<template>
  <div class="device-view">
    <h1>设备管理</h1>

    <!-- 搜索框和添加按钮在同一行 -->
    <div class="search-and-add-container">
      <el-input v-model="searchQuery" placeholder="请输入设备名称进行搜索" @keyup.enter="filterDevices"></el-input>
      <el-button @click="filterDevices">搜索</el-button>
      <el-button type="success" @click="openAddDialog">添加设备</el-button>
    </div>

    <el-table :data="filteredDevices" stripe>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="primary" @click="openEditDialog(row)">修改</el-button>
          <el-button type="danger" @click="confirmDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>

      <el-table-column prop="id" label="设备ID"></el-table-column>
      <el-table-column prop="name" label="设备名称"></el-table-column>
      <el-table-column prop="location" label="设备位置"></el-table-column>
      <el-table-column prop="description" label="设备描述"></el-table-column>
      <el-table-column prop="created_at" label="创建时间"></el-table-column>
    </el-table>

    <!-- 添加设备的弹窗 -->
    <el-dialog v-model="addDialogVisible" title="添加设备">
      <el-form :model="newDevice">
        <el-form-item label="设备名称">
          <el-input v-model="newDevice.name"></el-input>
        </el-form-item>
        <el-form-item label="设备位置">
          <el-input v-model="newDevice.location"></el-input>
        </el-form-item>
        <el-form-item label="设备描述">
          <el-input v-model="newDevice.description"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAdd">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改设备的弹窗 -->
    <el-dialog v-model="editDialogVisible" title="修改设备信息">
      <el-form :model="editDevice">
        <el-form-item label="设备名称">
          <el-input v-model="editDevice.name"></el-input>
        </el-form-item>
        <el-form-item label="设备位置">
          <el-input v-model="editDevice.location"></el-input>
        </el-form-item>
        <el-form-item label="设备描述">
          <el-input v-model="editDevice.description"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      devices: [],
      searchQuery: '',
      filteredDevices: [],
      editDialogVisible: false,
      editDevice: {},
      addDialogVisible: false,
      newDevice: {
        name: '',
        location: '',
        description: ''
      }
    };
  },
  created() {
    this.fetchDevices();
  },
  methods: {
    // 从数据库获取设备列表
    async fetchDevices() {
      try {
        const response = await axios.get('/api/devices'); // 假设 API 端点为 /api/devices
        this.devices = response.data;
        this.filteredDevices = [...this.devices];
      } catch (error) {
        console.error('获取设备列表失败:', error);
        this.$message.error('获取设备列表失败，请稍后再试');
      }
    },
    openEditDialog(device) {
      this.editDevice = {...device};
      this.editDialogVisible = true;
    },
    async saveEdit() {
      try {
        await axios.put(`/api/devices/${this.editDevice.id}`, this.editDevice); // 假设 API 端点为 /api/devices/:id
        const index = this.devices.findIndex(device => device.id === this.editDevice.id);
        if (index !== -1) {
          this.devices[index] = {...this.editDevice};
          this.filterDevices();
        }
        this.editDialogVisible = false;
        this.$message.success('设备信息修改成功');
      } catch (error) {
        console.error('修改设备失败:', error);
        this.$message.error('修改设备失败，请稍后再试');
      }
    },
    confirmDelete(id) {
      this.$confirm('确定要删除该设备吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteDevice(id);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    async deleteDevice(id) {
      try {
        await axios.delete(`/api/devices/${id}`); // 假设 API 端点为 /api/devices/:id
        this.devices = this.devices.filter(device => device.id !== id);
        this.filterDevices();
        this.$message.success('设备删除成功');
      } catch (error) {
        console.error('删除设备失败:', error);
        this.$message.error('删除设备失败，请稍后再试');
      }
    },
    filterDevices() {
      if (this.searchQuery === '') {
        this.filteredDevices = [...this.devices];
      } else {
        this.filteredDevices = this.devices.filter(device =>
            device.name.includes(this.searchQuery)
        );
      }
    },
    openAddDialog() {
      this.newDevice = {
        name: '',
        location: '',
        description: ''
      };
      this.addDialogVisible = true;
    },
    async saveAdd() {
      try {
        const newDeviceWithId = {
          ...this.newDevice,
          created_at: new Date().toISOString().split('T')[0]
        };
        const response = await axios.post('/api/devices', newDeviceWithId); // 假设 API 端点为 /api/devices
        this.devices.push(response.data);
        this.filterDevices();
        this.addDialogVisible = false;
        this.$message.success('设备添加成功');
      } catch (error) {
        console.error('添加设备失败:', error);
        this.$message.error('添加设备失败，请稍后再试');
      }
    }
  }
};
</script>

<style scoped>
.device-view {
  padding: 20px;
}

/* 搜索表单和添加按钮在同一行 */
.search-and-add-container {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.el-input {
  width: 300px; /* 调整搜索框宽度 */
}

/* 增加表格边框厚度 */
.el-table,
.el-table__header-wrapper,
.el-table__body-wrapper {
  border-width: 2px;
}

.el-table th.el-table__cell,
.el-table td.el-table__cell {
  border-width: 2px;
}
</style>